package com.zhkj.lib.widget

import android.content.Context
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.CycleInterpolator
import android.view.animation.TranslateAnimation
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import com.zhkj.lib.R

class ClearEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = androidx.appcompat.R.attr.editTextStyle
) : AppCompatEditText(context, attrs, defStyle), View.OnFocusChangeListener, TextWatcher {

    private val deleteIcon: Drawable =
        ContextCompat.getDrawable(context, R.drawable.cet_delete)!!.apply {
            setBounds(0, 0, intrinsicWidth, intrinsicHeight)
        }
    private var showDeleteIcon = false

    init {
        setDeleteIconVisible(false)
        onFocusChangeListener = this
        addTextChangedListener(this)
    }

    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        setDeleteIconVisible(hasFocus && !TextUtils.isEmpty(text))
    }

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        setDeleteIconVisible(!TextUtils.isEmpty(text))
    }

    override fun afterTextChanged(s: Editable?) {
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (showDeleteIcon) event?.let {
            if (it.action == MotionEvent.ACTION_UP) {
                val xTouchIcon = it.x > (width - paddingEnd - deleteIcon.intrinsicWidth) &&
                        it.x < width - paddingEnd
                if (xTouchIcon) text = null
            }
        }
        return super.onTouchEvent(event)
    }

    /**
     * 设置删除按钮是否显示
     */
    private fun setDeleteIconVisible(visible: Boolean) {
        val drawable = if (visible) deleteIcon else null
        setCompoundDrawables(
            compoundDrawables[0]?:compoundDrawablesRelative[0],
            compoundDrawables[1]?:compoundDrawablesRelative[1],
            drawable,
            compoundDrawables[3]?:compoundDrawablesRelative[3]
        )
        showDeleteIcon = visible
    }

    /**
     * 晃动提示
     */
    fun shake(count: Float) {
        val translate = TranslateAnimation(0F, 10F, 0F, 0F).apply {
            interpolator = CycleInterpolator(count)
            duration = 500
        }
        startAnimation(translate)
    }
}